# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '999361': {
        'API_KEY': 'uwds7kEGfBxNqUpfTB7uf76oam7zfvkB',
        'gateway': 'http://www.bfrim.cn/API/Bank/',
    },
    '421504': {  # dwc
        'API_KEY': 'WcAffKni096nzloKf7r1HVFUDqxJ6LIA',
        'gateway': 'http://yun.8au.com/API/Bank/',
    },
    '68955': {  # witch alipay
        'API_KEY': 'yeqInpaTErkWr49Sp2scXf3FTVlZONSr',
        'gateway': 'http://yun.8au.com/API/Bank/',
    },
    '658037': {  # loki alipay
        'API_KEY': 'ZBJfFnkpkfOMsLNZ3f10vofBEYhYyxmf',
        'gateway': 'http://yun.8au.com/API/Bank/',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_pay_type(service):
    if service == 'alipay':
        return '999'
    elif service == 'wxpay':
        return '7771'
    elif service == 'qq':
        return '555'
    else:
        return '999'


def generate_sign(d, key):
    '''  生成下单签名 '''
    s = 'LinkID={}&ForUserId={}&Channelid={}&Moneys={}&AssistStr={}&ReturnUrl={}&Key={}'.format(
        d['LinkID'], d['ForUserId'], d['Channelid'], d['Moneys'], d['AssistStr'], d['ReturnUrl'], key
    )
    _LOGGER.info("weibaopay sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('gb2312'))
    sign = m.hexdigest().lower()
    return sign


def generate_notify_sign(d, key):
    '''  生成下单签名 '''
    s = 'sErrorCode={}&bType={}&ForUserId={}&LinkID={}&Moneys={}&AssistStr={}&keyValue={}'.format(
        d['sErrorCode'], d['bType'], d['ForUserId'], d['LinkID'], d['Moneys'], d['AssistStr'], key
    ).lower()
    _LOGGER.info("weibaopay sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('gb2312'))
    sign = m.hexdigest().lower()
    return sign


def generate_query_sign(d, key):
    '''  生成下单签名 '''
    s = 'ForUserId={}&OrderId={}&Key={}'.format(
        d['ForUserId'], d['OrderId'], key
    )
    _LOGGER.info("weibaopay query sign str : %s", s)
    m = hashlib.md5()
    m.update(s.encode('gb2312'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("weibaopay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('LinkID', str(pay.id)),
        ('ForUserId', app_id),
        ('Channelid', _get_pay_type(service)),
        ('Moneys', str(pay_amount)),
        ('AssistStr', 'charge'),
        ('ReturnUrl', '{}/pay/api/{}/weibaopay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, app_id)),
        ('NotifyUrl', '{}/pay/api/{}/weibaopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['Sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("weibaopay create  data: %s, url: %s", parameter_dict, _get_gateway(app_id))
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    data = dict(request.GET.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("weibaopay notify data1: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['LinkID']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('weibaopay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['sErrorCode'])
    trade_no = pay_id
    total_fee = float(data['Moneys'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '1':
        _LOGGER.info('weibaopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('ForUserId', app_id),
        ('OrderId', str(pay_id)),
    ))
    parameter_dict['Sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info("weibaopay query  data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("weibaopay query  rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['Status'])
        trade_no = ''
        total_fee = float(data['RealMoney'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # 为0表示成功，为1表示失败
        if trade_status == '0':
            _LOGGER.info('weibaopay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('weibaopay data error, status_code: %s', response.status_code)
